#Conduct Multiple Imputation
rm(list=ls())
if(!is.null(sessionInfo()$otherPkgs)){
  invisible(lapply(paste0('package:', names(sessionInfo()$otherPkgs)), detach, character.only=TRUE, unload=TRUE))  
}

if (!require(pacman)){
  install.packages(pacman)
  library(pacman)
}

p_load(dplyr,stringr,readr,stringi,haven,matrixStats,labelled,mice)

dat <- readRDS("../Data/clean_data.RDS") %>% remove_labels()
dat$hist[is.na(dat$hist)] <- 99
set.seed(08536)
factors <- dat %>% dplyr::select_if(is.factor)
dat$territ_loss_concern_scaled <- as.vector(dat$territ_loss_concern_scaled)
datimpute <- dat %>% dplyr::select_if(is.numeric) %>% mice(.,method="cart")
datimpute <- as.mids(complete(datimpute,"long",include=T) %>% bind_cols(bind_rows(replicate(6,factors,simplify = F))))
saveRDS(datimpute,"../Data/data_imputed.RDS")

